package vip.xiaonuo.app.modular.auth.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;

import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.app.core.consts.AppConstant;
import vip.xiaonuo.app.modular.auth.service.AppAuthService;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.exception.enums.ParamException;
import vip.xiaonuo.core.exception.enums.ParamExceptionEnum;
import vip.xiaonuo.core.pojo.response.ErrorResponseData;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.core.util.HttpServletUtil;
import vip.xiaonuo.core.util.IpAddressUtil;
import vip.xiaonuo.sys.core.cache.RedisCache;
import vip.xiaonuo.sys.modular.sms.enums.SmsSendSourceEnum;
import vip.xiaonuo.sys.modular.sms.param.SysSmsSendParam;
import vip.xiaonuo.sys.modular.sms.service.SmsSenderService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


/**
 * <p>Title : app权鉴</p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows11</p>
 *
 * @Author : zxw
 * @Date 2023/9/11 15:53
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {

    @Resource
    private RedisCache redisCache;
    @Resource
    private AppAuthService appAuthService;
    @Resource
    private SmsSenderService smsSenderService;


    /**
     * 账号密码登录注册
     *
     * @param dict
     * @return
     */
    @PostMapping("/login")
    public ResponseData login(@RequestBody Dict dict) {
        String loginName = dict.getStr("loginName");
        String passWord = dict.getStr("passWord");
        String smsCode = dict.getStr("smsCode");
        String token = appAuthService.initLogin(loginName, passWord, smsCode);
        return ResponseData.success(token);
    }


    /**
     * 获取短信验证码
     */
    @PostMapping("/sendSms")
    public ResponseData sendSms(@RequestBody SysSmsSendParam sysSmsSendParam) {
        //验证最近120秒内是否有发送过短信
        final String SMSSendRedis = "SMS_SEND_REDIS:";
        String phoneNumbers = sysSmsSendParam.getPhoneNumbers();
        String ip = IpAddressUtil.getIp(HttpServletUtil.getRequest());
        //拼接
        String redisKey = SMSSendRedis + phoneNumbers + ip;
        if (redisCache.getCache(redisKey) != null) {
            return new ErrorResponseData(500, "验证码请求过于频繁");
        }
        // 设置模板中的参数
        HashMap<String, Object> paramMap = CollectionUtil.newHashMap();
        paramMap.put("code", RandomUtil.randomNumbers(AppConstant.CONSTANT_SIX)); //随机6位数
        paramMap.put("areaCode", sysSmsSendParam.getAreaCode()); //设置国家代码
        sysSmsSendParam.setSmsSendSourceEnum(SmsSendSourceEnum.APP); //

        switch (sysSmsSendParam.getSendType()) {
            case "1":
                //登录验证码
                sysSmsSendParam.setTemplateCode(ConstantContextHolder.getSmsBaoConfigs().getTemplateCode());
                break;
            default:
                throw new ParamException(ParamExceptionEnum.PARAM_ERROR);
        }
        sysSmsSendParam.setParams(paramMap);
        //
        boolean b = smsSenderService.sendShortMessage(sysSmsSendParam);
        //
        if (b) {
            // 添加缓存防止重复发送短信
            redisCache.setCache(redisKey, new Date(), 120L, TimeUnit.SECONDS);
        }
        return new SuccessResponseData(b);
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/getLoginUser")
    public ResponseData getLoginUser() {

        //登录获取token 执行spring 上下文
        return ResponseData.success(LoginContextHolder.me().getAppLoginUserUpToDate());
    }


    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public ResponseData logout() {

        appAuthService.logout();
        return new SuccessResponseData();
    }


    /**
     * test
     */
//    @GetMapping("/testRedis")
//    public ResponseData testRedis() {
//
//        HashMap<String, String> map = new HashMap<>();
//        map.put("1", "1-1");
//        map.put("1", "2-2");
//        map.put("1", "3-3");
//        map.put("1", "4-4");
//        map.put("1", "hahahah");
//        redisCache.setCache("redisLoginUuidKey", map);
//        //获取
//        Object obj = redisCache.getCache("redisLoginUuidKey");
//        HashMap<String, String> maps = (HashMap<String, String>) obj;
//        String s = maps.get("1");
//        System.out.println(s);
//        return ResponseData.success();
//    }


}
